package fr.xelaprod.open.source.android.rss.db;

import java.util.HashMap;
import java.util.Map;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
/**
 * 
 * @author alexandre thery
 *
 */
public class MyNewsHandleBDD {

	private static final int VERSION_BDD = 1;
	private static final String NOM_BDD = "settings_info";
 
	private static final String TABLES = "my_news_table";
	private static final String ID = "id";
	private static final String TITLE = "title";

	private SQLiteDatabase bdd;
 
	private MyNewsDatabase database;
 
	public MyNewsHandleBDD(Context context){
		database = new MyNewsDatabase(context, NOM_BDD, null, VERSION_BDD);
	}
 
	public void open(){
		bdd = database.getWritableDatabase();
	}
 
	public void close(){
		bdd.close();
	}
 
	public SQLiteDatabase getBDD(){
		return bdd;
	}
 
	public long insertItem(String item){

		ContentValues values = new ContentValues();
		values.put(TITLE, item);
		return bdd.insert(TABLES, null, values);
	}
 

	public int removeInfoWithID(int id){
		return bdd.delete(TABLES, ID + " = " +id, null);
	}

	public String getItem(int id){
		Cursor c = bdd.query(TABLES, new String[] {TITLE}, ID+" = " + id, null, null, null, null);
		return cursorToItem(c);
	}
	public int getLastElement()
	{
		Cursor c = bdd.query(TABLES, new String[] {TITLE}, null, null, null, null, null);
		if(c!=null)
			return c.getCount();
		return 0;
	}
	public String cursorToItem(Cursor c){
		if (c.getCount() == 0)
			return null;
		c.moveToFirst();
		String text = c.getString(0);
		c.close();
		return text;
	}
	public Map<Integer, String> getItems()
	{
		Map<Integer, String> map = new HashMap<Integer, String>();
		Cursor c = bdd.query(TABLES, new String[] {ID,TITLE}, null, null, null, null, null);
		if (c.getCount() == 0)
			return null;
		else{
			int id;
			String txt;
			c.moveToFirst();
			id = c.getInt(0);
			txt = c.getString(1);
			map.put(id, txt);
			while(!c.isLast())
			{
				c.moveToNext();
				id = c.getInt(0);
				txt = c.getString(1);
				map.put(id, txt);
			}
			c.close();
		}
		return map;
		
	}
}
